import router from '@/router/index'
import store from './store'
import NProgress from 'nprogress' // 引入NProgress
import 'nprogress/nprogress.css' // 引入进度条的样式
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router/index'

// 设置白名单
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // to and from are both route objects. must call `next`.
  // console.log(to.path, '去哪里')
  // console.log(from.path, '从哪里来')
  document.title = getPageTitle(to.meta.title)
  next()
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    // 已经登录了
    if (to.path === '/login') {
      // console.log('已经登陆了,不能去登录页,跳转到首页')
      next('/') // next如果指定了地址进行跳转,那么不会经过router.afterEach需要手动关闭进度条
      NProgress.done()
    } else {
      // console.log('已经登录,不是去登录页放行')
      if (!store.getters.userId) {
        const menus = await store.dispatch('user/setUserInfo')
        // 在这里获取权限的信息, 实现权限控制
        console.log(menus, 'menus')
        console.log(asyncRoutes, 'asyncRoutes')
        // menus===>{'employees','settings','permissions'}
        // 根据权限信息进行过滤得到用户可以访问的路由表
        const filterRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        console.log(filterRoutes, 'filterRoutes')
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menu/setMenuList', filterRoutes)
        next({ ...to, replace: true })
      } else {
        next() // 放行到首页
      }
    }
  } else {
    // 没有登录
    if (whiteList.includes(to.path)) {
      // console.log('已经有白名单,直接放行')
      next()
      NProgress.done()
    } else {
      // console.log('没有登陆,不能去首页页,跳转到登录页')
      next('/login')
    }
  }
})
// 页面跳转完成,关闭进度条
router.afterEach(() => {
  NProgress.done()
})

